// static/js/change_pwd.js
;(function(){
  const form   = document.getElementById('change-pwd-form');
  const errEl  = document.getElementById('changePwdError');

  // 打开时清空错误
  document.getElementById('changePwdModal')
    .addEventListener('show.bs.modal', () => {
      errEl.style.display = 'none';
      errEl.textContent = '';
      form.reset();
    });

  form.addEventListener('submit', async e => {
    e.preventDefault();
    errEl.style.display = 'none';
    errEl.textContent = '';

    const data = {
      old_password: form.old_password.value,
      new_password: form.new_password.value,
      confirm:      form.confirm.value
    };

    try {
      const res = await fetch('/api/password/change', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      const text = await res.text();
      let payload;
      try { payload = JSON.parse(text); }
      catch { throw new Error(text); }

      if (!res.ok) {
        throw new Error(payload.error || payload.message || '修改失败');
      }

      // 修改成功
      form.closest('.modal').querySelector('[data-bs-dismiss="modal"]').click();
      alert('密码已修改，请重新登录');
      // 可选：登出后跳转登录页
      window.location.href = '/logout';
    } catch (err) {
      errEl.textContent = err.message;
      errEl.style.display = 'inline';
      setTimeout(() => { errEl.style.display = 'none'; }, 3000);
    }
  });
})();
